package com.cloudfun.campusshare.schedule;

import com.cloudfun.campusshare.entity.AttachmentEntity;
import com.cloudfun.campusshare.repo.AttachmentEntityRepo;
import com.cloudfun.campusshare.service.AttachmentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Huqin on 2020/4/11
 */
@Slf4j
@Component
public class AttachmentCleanSchedule extends BaseScheduleTask {

    @Autowired
    private AttachmentService attachmentService;

    @Autowired
    private AttachmentEntityRepo attachmentEntityRepo;

    /**
     * 每小时执行
     */
    // @Scheduled(fixedRate = 60 * 60 * 1000)
    public void changeBidStatus() {
        this.execute();
    }

    @Override
    protected String getTaskName() {
        return "附件清理";
    }

    @Override
    protected void doExecute() {
        Date now = new Date();
        Date nowMinus3Hour = DateUtils.addHours(now, -1);
        List<AttachmentEntity> attachmentEntities = attachmentEntityRepo.findAllBySubjectIdIsNull();
        List<AttachmentEntity> needCleanEntities = attachmentEntities.stream().filter(attachment -> {
            // 如果没有主体id，且修改时间在1小时以前，则清理掉
            Date updateTime = new Date(Long.parseLong(attachment.getUpdateTime()));
            return updateTime.before(nowMinus3Hour);
        }).collect(Collectors.toList());
        attachmentService.deleteAttachment(needCleanEntities);
    }

}
